package com.myreminder.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.util.logging.resources.logging;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.myreminder.data.ExpiredReminder;
import com.myreminder.data.Reminder;
import com.myreminder.data.User;

/**
 * The server side implementation of the RPC service.
 */


@SuppressWarnings("serial")
public class WorkerServlet extends RemoteServiceServlet  {
	
	private static final Logger log = Logger.getLogger(WorkerServlet.class.getName());
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	    new DAO();
	    Objectify ofy = ObjectifyService.begin();
	    Query<Reminder> query = ofy.query(Reminder.class).filter("datum <=", new Date());
	    for (Reminder r: query) {
	        handleExpiredReminder(r);
	    }
	}
	
	private void handleExpiredReminder(Reminder r){
		new DAO();
		Objectify ofy = ObjectifyService.begin();
		try{
			User u = ofy.get(r.user);
			
			String postitReminder = "<div style=\"position: relative; overflow-x: hidden; overflow-y: hidden; width: 342px; height: 229px; background-image: url(http://my-simple-reminder.appspot.com/images/postit_reminder.png);\">" +
				"<div style=\"position: absolute; left: 45px; top: 35px; width: 160px; \">"+r.titel+"</div>" +
				"<div style=\"position: absolute; left: 45px; top: 70px; width: 229px;\">"+r.description+"</div>" +
				"<div style=\"position: absolute; left: 225px; top: 35px; width: 50px; \">"+r.datum+"</div>" +
				"</div>";
			sendEmail(u.email,r.titel,postitReminder);
			ExpiredReminder er = new ExpiredReminder(r.user, r.datum, r.titel, r.description, new Date(), u.email);
			ofy.delete(r);
			ofy.put(er);
			//ofy.getTxn().commit();
			log.info("Reminder sent: "+r.toString());
		} catch (Exception e){
			//ofy.getTxn().rollback();
			log.severe("Error handleExpiredReminder: "+r.toString());
		}
	}

	private void sendEmail(String address, String subject, String content) throws Exception{
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress("Reminder@my-simple-reminder.appspotmail.com","myReminder"));
		msg.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
		msg.setSubject(subject);
		//msg.setText(content);
		//msg.setContent(content, "text/html");
		msg.setText(content,"utf-8","html");
		Transport.send(msg);
	}
}
